//
//  FFPayOrderAddAddressView.m
//  FFMall
//
//  Created by ale tan on 2017/9/21.
//  Copyright © 2017年 IT.Bear. All rights reserved.
//

#import "FFPayOrderAddAddressView.h"

#import "FFPayOrderChooseCountryView.h"
#import "FFAddressView.h"
#import "FFLocationManager.h"

#import "GetCountryRequest.h"
#import "GetAddressRequest.h"

@interface FFPayOrderAddAddressView ()<UITextFieldDelegate>

@property (nonatomic ,strong) AddNewAddress addNewAddressBlock;

@property (nonatomic ,strong) FBCountryModel *countryModel;
@property (nonatomic ,assign) NSInteger countryIndex;

@property (weak, nonatomic) IBOutlet UILabel *countryNameLabel;
@property (weak, nonatomic) IBOutlet UITextField *nameTextField;
@property (weak, nonatomic) IBOutlet UITextField *phoneTextField;
@property (weak, nonatomic) IBOutlet UITextField *districtTextField;
@property (weak, nonatomic) IBOutlet UITextField *detailTextField;
@property (weak, nonatomic) IBOutlet UIButton *isDefaultButton;
@property (weak, nonatomic) IBOutlet UITextField *cardTextField;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *showIDCardHeight;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *toBottom;
@end

@implementation FFPayOrderAddAddressView

+ (instancetype)addressView{
    FFPayOrderAddAddressView *orderView = [[[NSBundle mainBundle] loadNibNamed:@"FFPayOrderAddAddressView" owner:nil options:nil] firstObject];
    orderView.countryIndex = -1;
    [[FFLocationManager sharedInstance] handlerAddressList];
    return orderView;
}

- (void)show{
    UIView *view = [UIApplication sharedApplication].keyWindow.rootViewController.view;//[[UIApplication sharedApplication].delegate window];
    self.frame = view.bounds;
    [self layoutIfNeeded];
    [view addSubview:self];
}

- (void)setAddNewAddress:(AddNewAddress)addNewAddress{
    _addNewAddressBlock = addNewAddress;
}

- (void)setAddress:(FBAddressModel *)address{
    _address = address;
    
    //国家
    _countryNameLabel.text = _address.addressCountry;
    if ([address.addressCountry isEqual:@"中国"]) {
        _districtTextField.placeholder = @"省/市/区";
        _showIDCardHeight.constant = 44;
    }
    else{
        _districtTextField.placeholder = @"州/省/地区";
        _showIDCardHeight.constant = 0;
    }
    
    //名字
    if (address.consigneeName) {
        _nameTextField.text = address.consigneeName;
    }
    
    //电话号码
    if (address.consigneePhone) {
        _phoneTextField.text = address.consigneePhone;
    }
    
    //身份证
    if (_address.consigneeIdcard) {
        _cardTextField.text = _address.consigneeIdcard;
    }
    
    //地址
    if (_address.address) {
        NSString *detailAddress = [[_address.address componentsSeparatedByString:@" "] lastObject];
        NSString *district = [_address.address stringByReplacingOccurrencesOfString:detailAddress withString:@""];
        _districtTextField.text = district;
        _detailTextField.text = detailAddress;
    }
    
}

- (void)awakeFromNib{
    [super awakeFromNib];
    _toBottom.constant = isDeviceIphoneX?34:0;
    _districtTextField.delegate = self;
    _cardTextField.delegate = self;
}

#pragma mark -UITextFieldDelegate-
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    if ([textField isEqual:_districtTextField]) {
        if (_countryModel && ![_countryModel.chinese_name isEqual:@"中国"]) {
            return YES;
        }
        else{
            [self pickProvinces];
            return NO;
        }
    }
    else{
        return YES;
    }
}

- (void)textFieldDidEndEditing:(UITextField *)textField{
    if ([textField isEqual:_cardTextField]) {
        if (textField.text.length) {
            //正确的身份证号
            if (![GetAddressRequest isValidIDCard:textField.text]) {
                [FFTipsView showTips:@"请输入正确的身份证号"];
            }
        }
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if ([textField isEqual:_cardTextField]) {
        NSString *card = [textField.text stringByAppendingString:string];
        if (card.length>18) {
            return NO;
        }
    }
    
    return YES;
}

#pragma makr -Events-
- (IBAction)clickBackgroundToCancle:(id)sender {
    [self removeFromSuperview];
}

//取消
- (IBAction)clickToCancleAddNewAddress:(UIButton *)sender {
    [self removeFromSuperview];
    if (_addNewAddressBlock) {
        _addNewAddressBlock(nil);
    }
}

//确定添加地址
- (IBAction)clickToSaveNewAddress:(UIButton *)sender {
    if (!_nameTextField.text.length) {
        [FFTipsView showTips:@"请输入收货人姓名"];
        return;
    }
    
    if (!_phoneTextField.text.length) {
        [FFTipsView showTips:@"请输入手机号码"];
        return;
    }
    
    if (!_districtTextField.text.length) {
        [FFTipsView showTips:@"请输入/选择地区"];
        return;
    }
    
    if (!_detailTextField.text.length) {
        [FFTipsView showTips:@"请输入详细地址"];
        return;
    }
    
    if (!_cardTextField.text.length && !(_countryModel && ![_countryModel.chinese_name isEqual:@"中国"])) {
        [FFTipsView showTips:@"请输入身份证号码"];
        return;
    }
    
    //新增地址
    if (!_address) {
        _address = [FBAddressModel new];
        
        //国家
        if (_countryModel) {
            _address.countryCode = _countryModel.chinese_name;
            _address.countryCode = _countryModel.code;
        }
        else{
            _address.addressCountry = @"中国";
            _address.countryCode = @"+86";
        }
        
        _address.consigneeName = _nameTextField.text;
        _address.consigneePhone = _phoneTextField.text;
    
        NSString *userAddress = [NSString stringWithFormat:@"%@ %@",_districtTextField.text,_detailTextField.text];
        _address.address = userAddress;
        _address.isDefault = _isDefaultButton.selected?@"true":@"false";
        //中国必传身份证
        if (!(_countryModel && ![_countryModel.chinese_name isEqual:@"中国"])) {
            _address.consigneeIdcard = _cardTextField.text;
        }
        
        WS(weakSelf);
        GetAddressRequest *createReq = [GetAddressRequest new];
        [createReq addAddressWithModel:_address Complete:^(id responseDic, BOOL result) {
            if (result) {
                FBAddressModel *model = (FBAddressModel *)responseDic;
                [weakSelf removeFromSuperview];
                if (weakSelf.addNewAddressBlock) {
                    weakSelf.addNewAddressBlock(model);
                }
            }
        }];
    }
    //编辑地址
    else{
        //国家
        if (_countryModel) {
            _address.addressCountry = _countryModel.chinese_name;
            _address.countryCode = _countryModel.code;
        }
        
        _address.consigneeName = _nameTextField.text;
        _address.consigneePhone = _phoneTextField.text;
        
        //中国必传身份证
        if (!(_countryModel && ![_countryModel.chinese_name isEqual:@"中国"])) {
            if (![_cardTextField.text containsString:@"*"]) {
                _address.consigneeIdcard = _cardTextField.text;
            }
        }
        
        NSString *userAddress = [NSString stringWithFormat:@"%@ %@",_districtTextField.text,_detailTextField.text];
        _address.address = userAddress;
        _address.isDefault = _isDefaultButton.selected?@"true":@"false";
        
        WS(weakSelf);
        GetAddressRequest *req = [GetAddressRequest new];
        [req editAddressWithModel:_address Complete:^(id responseDic, BOOL result) {
            if (result) {
                FBAddressModel *model = (FBAddressModel *)responseDic;
                [weakSelf removeFromSuperview];
                if (weakSelf.addNewAddressBlock) {
                    weakSelf.addNewAddressBlock(model);
                }
            }
        }];
    }
    
}

//选择国家
- (IBAction)clickToChooseCountry:(UIButton *)sender {
    [self endEditing:YES];
    GetCountryRequest *request = [[GetCountryRequest alloc]init];
    WS(weakSelf);
    [request requestForCountiesWithCallBack:^(NSDictionary *responseDic, BOOL result) {
        if (result) {
            NSMutableArray *countries = [NSMutableArray array];
            NSArray *array = (NSArray *)responseDic;
            for (NSDictionary *dic in array) {
                if (![dic[@"index"] isEqual:@"#"]) {
                    NSArray *letterArr = dic[@"names"];
                    [countries addObjectsFromArray:letterArr];
                }
            }
            
            if (weakSelf.countryIndex<0) {
                for (int i=(int)countries.count-1; i>=0; i--) {
                    FBCountryModel *country = countries[i];
                    if ([country.chinese_name isEqual:@"中国"]) {
                        weakSelf.countryModel = country;
                        weakSelf.countryIndex = i;
                        break;
                    }
                }
            }
            
            FFPayOrderChooseCountryView *chooseCountryView = [FFPayOrderChooseCountryView chooseCountryViewWithCountries:countries SelectedIndex:weakSelf.countryIndex];
            
            self.hidden = YES;
            [chooseCountryView setChooseCountry:^(FBCountryModel *model,NSInteger countryIndex) {
                if (countryIndex>=0) {
                    weakSelf.countryModel = model;
                    weakSelf.countryIndex = countryIndex;
                    _countryNameLabel.text = model.chinese_name;
                    
                    if ([model.chinese_name isEqual:@"中国"]) {
                        _districtTextField.placeholder = @"省/市/区";
                        _showIDCardHeight.constant = 44;
                    }
                    else{
                        _districtTextField.placeholder = @"州/省/地区";
                        _showIDCardHeight.constant = 0;
                    }
                    
                    _districtTextField.text = @"";
                    _detailTextField.text = @"";
                }
                
                self.hidden = NO;
            }];
            [chooseCountryView show];
        }
    }];
}

//选择是否设为默认
- (IBAction)clickToSetDefault:(id)sender {
    _isDefaultButton.selected = !_isDefaultButton.selected;
}

//选择省市区
- (void)pickProvinces{
    [self endEditing:YES];
    self.hidden = YES;
    FFAddressView * addressView = [[FFAddressView alloc]initWithRegions:[FFLocationManager sharedInstance].regionList];
    addressView.isShowDistrict = NO;
    
    WS(weakSelf);
    if (self.districtTextField.text.length) {
        NSArray *areaInfo = [self.districtTextField.text componentsSeparatedByString:@" "];

        if ([areaInfo isKindOfClass:[NSArray class]]) {
            
            NSString *p = areaInfo[0];
            NSString *c = areaInfo[1];
            NSString *d = areaInfo[2];
            NSString *s = @"";//areaInfo[3];
            
            [addressView showWithProvince:p city:c district:d street:s callback:^(BOOL selected, NSString *p, NSString *c, NSString *d, NSString *s, NSString *pID, NSString *cID, NSString *dID, NSString *sID) {
                weakSelf.hidden = NO;
                if (selected) {
                    NSString *address = [NSString stringWithFormat:@"%@ %@ %@",p,c,d];
                    _districtTextField.text = address;
                }
            }];
        }
    }
    else{
        [addressView show:^(BOOL selected, NSString *p, NSString *c, NSString *d, NSString *s, NSString *pID, NSString *cID, NSString *dID, NSString *sID) {
            weakSelf.hidden = NO;
            if (selected) {
                NSString *address = [NSString stringWithFormat:@"%@ %@ %@",p,c,d];
               _districtTextField.text = address;
            }
        }];
    }
}


@end
